package com.dragonfly.shutter.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dragonfly.shutter.beans.Message;
import com.dragonfly.shutter.services.ScoreService;
import com.dragonfly.shutter.utils.KeywordFilter;

/**
 * 用户评分控制器
 * @author 黄挺
 *
 */
@Controller
@RequestMapping("/score.html")
public class ScoreController {
	@Autowired
	private ScoreService scoreService;
	
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onSubmit(HttpSession session, HttpServletRequest request,
			@RequestParam(value="pictureID", required=false) String pictureID,
			@RequestParam(value="ownerID", required=false) String ownerIDStr,
			@RequestParam(value="score", required=false) String scoreStr){
		Integer userID = (Integer) session.getAttribute("userID");
		Message message = null;
		
		//用户是否登录
		if(userID == null){
			message = new Message("您尚未登录，请先登录", "未登录", "login.html");
			return new ModelAndView("message", "message", message);
		}
		
		//空的参数
		if(pictureID == null || ownerIDStr == null || scoreStr == null ){
			message = new Message("空的参数", "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}
		
		//非法的参数
		if(!KeywordFilter.isNumeric(ownerIDStr) || !KeywordFilter.isNumeric(pictureID) ||
				!KeywordFilter.isNumeric(scoreStr)){
			message = new Message("非法的参数", "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}
		
		Integer ownerID = Integer.parseInt(ownerIDStr);
		Integer score = Integer.parseInt(scoreStr);
		
		//错误的评分
		if(score<=0 || score>5){
			message = new Message("错误的评分", "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}
		
		if(userID == ownerID){
			message = new Message("您无法给自己的图片评分", "操作失败", "picture.html?pictureID="+pictureID);
			return new ModelAndView("message", "message", message);
		}

		scoreService.doService(userID, pictureID, score, request.getRequestURL().toString());
		return new ModelAndView("redirect:/picture.html?pictureID=" + pictureID);
	}
}
